from django.shortcuts import render
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from random import randint
from libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from rest_framework import status
# Create your views here.

class RegisterImageCodeView(APIView):
    """
    生成验证码的接口
    GET  /verifications/imagecodes/(?P<image_code_id>.+)/

    """

    def get(self,request,image_code_id):

        #生成图片和验证码
        text,image = captcha.generate_captcha()

        #把验证码保存到redis中
        redid_conn = get_redis_connection('code')
        redid_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        #返回图片
        return HttpResponse(image,content_type='image/jpeg')


class RegisterSMSCodeView(GenericAPIView):
    """
    根据用户提交的验证码，发送验证码
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx


    1.先校验验证码
    2.校验成功，给手机发送验证码
    3.把短信存起来，设置有效期
    4.我们需要设置发送的标记，防止频繁操作
    """

    serializer_class = RegisterSMSCodeSerializer
    def get(self,request,mobile):

        #1.验证码内容的校验（序列化器）
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        #2.判断用户是否有发送记录，防止用户频繁操作
        redis_coon = get_redis_connection('code')

        flag = redis_coon.get('sms_flag_%s'%mobile)
        if flag:
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)

        #3.生成短信验证码
        sms_code = '%06d'%randint(0,999999)
        #4.记录发送状态

        #短信验证码记录
        # redis_coon.setex('sms_%s'%mobile,constants.SMS_CODE_EXPIRE_TIME,sms_code)
        # #记录发送状态
        # redis_coon.setex('sms_flag_%s'%mobile,60,1)

        #创建管道
        pl = redis_coon.pipeline()
        #将我们的指令放到管道中  等待统一执行
        pl.setex('sms_%s'%mobile,constants.SMS_CODE_EXPIRE_TIME,sms_code)
        pl.setex('sms_flag_%s'%mobile,60,1)

        #执行
        pl.execute()

        #发送
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        return Response({'message':'ok'})